<?php
// test
class Ws{
    const Host = '0.0.0.0';
    const Port = '8082';
    const Document = __DIR__ . '/public';

    protected $ws = null;
    function __construct(){
        $this->ws = new Swoole\Websocket\Server(self::Host, self::Port);
        // 设置静态路由
        $this->ws->set([
            'worker_num' => 2,
            'task_worker_num' => 4,
            'enable_static_handler' => true, // 静态路由支持
            'document_root' => self::Document // 静态文件根目录
        ]);

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);
        $this->ws->on('Task',[$this, 'onTask']); // 异步任务的回调
        $this->ws->on('Finish',[$this, 'onFinish']); // 任务完成的回调

        $this->ws->start();
    }

    public static function onOpen($ws, $request){
        echo "client {$request->fd} is comming \n";
        $ws->push($request->fd, 'hello');
    }

    public function onMessage($ws, $frame){
        echo "<< {$frame->data} \n";
        // 假如有个超级耗时的任务5s才能完成
        $taskData = [
            'fd' => $frame->fd,
            'message' => '-s-s-s-s-s-s-s-'
        ];
        $ws->task($taskData); // 投递任务
        if (is_numeric($frame->data)) {
            $ws->push($frame->fd, $frame->data + 1);
        }
    }

    public function onTask($serv, $taskId, $workerId, $data){
        echo  "task {$taskId} start\n";;
        $data['start'] = date('Y-m-d H:i:s');
        // 处理一个非常耗时的任务
        sleep(5);
        $data['finined'] = date('Y-m-d H:i:s');
        return $data;
    }

    public function onFinish($serv, $taskId, $data){
        echo "task {$taskId} Fininsed\n";
        // 监听到一个任务完成了 发数据给客户端
        $sendData = json_encode($data);
        $serv->push($data['fd'], $sendData);
        echo ">> {$sendData}\n";
    }
    
    public function onClose($ws, $fd){
        echo "client {$fd} closed \n";
    }
}

new Ws();